package admin.controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entities.Staff;

import admin.forms.StaffForm;
import admin.models.StaffModel;

public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		
		TreeMap check = new TreeMap();
		Staff user = new Staff();
		
		if (session.getAttribute("staff_logged_in") != null) {
			response.sendRedirect("/admin/dashboard");
			return ;
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/admin/pages/login.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		
		if (session.getAttribute("staff_logged_in") != null) {
			response.sendRedirect("/profile");
			return ;
		}
		
		StaffModel staffModel = StaffModel.getInstance();
		Staff user = new Staff();
		
		TreeMap form = (TreeMap) StaffForm.checkLogin(request, user);
		
		user = (Staff) form.get("user");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			Staff staff = staffModel.getByUsername(user.getUsername());
			if (staff != null) {
				if (!StringHelper.md5(user.getPassword()).equalsIgnoreCase(staff.getPassword())) {
					request.setAttribute("error", "Password incorrect.");
				} else {
					//Save login to session
					session.setAttribute("staff_logged_in", staff);
					response.sendRedirect("/admin/dashboard");
					return ;
				}
			} else {
				request.setAttribute("error", "Username incorrect.");
			} 
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/admin/pages/login.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
